package ps

import (
	"context"
	"fmt"
	"github.com/Unixeno/islands/cmd/connection"
	"github.com/Unixeno/islands/cmd/image"
	"github.com/Unixeno/islands/cmd/utils"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/gosuri/uitable"
	"github.com/spf13/cobra"
	"strings"
	"time"
)

var all bool

func GetPsCmd() *cobra.Command {
	psCmd := &cobra.Command{
		Use:   "ps",
		Short: "list the container",
		Long:  `list containers in your islands`,
		Args:  cobra.MinimumNArgs(0),
		Run:   psHandle,
	}

	psCmd.Flags().BoolVarP(&all, "all", "a", false, "Show all containers (default shows just running)")
	return psCmd
}

func psHandle(cmd *cobra.Command, args []string) {
	r, err := connection.Client.ListContainer(context.Background(), &empty.Empty{})

	if err != nil {
		fmt.Printf("Cannot list the container for reason %v\n", err)
	} else {
		if !utils.PrintError(r.Err) {
			table := uitable.New()
			table.MaxColWidth = 50

			table.AddRow("ID", "NAME", "IMAGE", "IMAGEID", "COMMAND", "CREATED", "STATUS")

			for _, v := range r.Containers {
				if t, err := time.Parse(image.TIME_LAYOUT, strings.Split(v.Created, " m=")[0]); err != nil {
					fmt.Println(err)
					return
				} else {
					if all {
						table.AddRow(
							utils.CheckLength(v.Id),
							utils.CheckLength(v.Name),
							utils.CheckLength(v.Image),
							utils.CheckLength(v.ImageId),
							`"`+utils.CheckLength(v.Command)+`"`,
							t.Format("2006-01-02 15:04:05"),
							v.State,
						)
					} else {
						if v.State == "Running" {
							table.AddRow(
								utils.CheckLength(v.Id),
								utils.CheckLength(v.Name),
								utils.CheckLength(v.Image),
								utils.CheckLength(v.ImageId),
								`"`+utils.CheckLength(v.Command)+`"`,
								t.Format("2006-01-02 15:04:05"),
								v.State,
							)
						}
					}
				}
			}
			fmt.Println(table)
		}
	}
}
